from rest_framework import serializers
from django.contrib.auth import get_user_model
from django.contrib.auth.password_validation import validate_password

User = get_user_model()

class LoginSerializer(serializers.Serializer):
    """登录序列化器"""
    email = serializers.EmailField(required=True)
    password = serializers.CharField(required=True, write_only=True)

class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    password = serializers.CharField(write_only=True, required=True, validators=[validate_password])
    password2 = serializers.CharField(write_only=True, required=False)

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'password2', 'email', 'phone', 'first_name', 'last_name')
        extra_kwargs = {
            'username': {'required': False},
            'first_name': {'required': False},
            'last_name': {'required': False},
            'email': {'required': True},
            'phone': {'required': False}
        }

    def validate(self, attrs):
        if 'password2' in attrs and attrs['password'] != attrs['password2']:
            raise serializers.ValidationError({"password": "两次密码不匹配"})
        return attrs

    def create(self, validated_data):
        if 'password2' in validated_data:
            validated_data.pop('password2')
        # 如果没有提供用户名，使用邮箱的用户名部分作为默认用户名
        if not validated_data.get('username'):
            email = validated_data.get('email')
            validated_data['username'] = email.split('@')[0]
        user = User.objects.create_user(**validated_data)
        return user

class ResetPasswordRequestSerializer(serializers.Serializer):
    """请求重置密码的序列化器（发送验证码）"""
    email = serializers.EmailField(required=True)

    def validate_email(self, value):
        try:
            User.objects.get(email=value)
            return value
        except User.DoesNotExist:
            raise serializers.ValidationError("该邮箱未注册")

class ResetPasswordSerializer(serializers.Serializer):
    """重置密码序列化器（验证验证码并重置密码）"""
    email = serializers.EmailField(required=True)
    code = serializers.CharField(required=True)
    new_password = serializers.CharField(required=True, validators=[validate_password])

    def validate(self, attrs):
        from .verification import verify_code
        
        email = attrs['email']
        code = attrs['code']
        
        # 验证邮箱是否存在
        try:
            user = User.objects.get(email=email)
            attrs['user'] = user
        except User.DoesNotExist:
            raise serializers.ValidationError({"email": "该邮箱未注册"})
        
        # 验证验证码
        if not verify_code(email, code):
            raise serializers.ValidationError({"code": "验证码错误或已过期"})
        
        return attrs

class UserDetailSerializer(serializers.ModelSerializer):
    """用户详情序列化器"""
    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'phone', 'first_name', 'last_name', 'date_joined', 'last_login')
